/**
 * 
 */
package cn.ad.server.web.servlet.v2.requesthandler;

import cn.ad.server.web.servlet.v2.parser.AdRequestParseException;
import cn.ad.server.web.servlet.v2.parser.HttpServletParser;
import cn.ad.server.web.spring.model.BidAdRequest;
import cn.ad.server.web.spring.model.BidAdResponse;
import cn.ad.server.web.spring.model.IAdserverRequest;
import cn.ad.server.web.spring.service.actions.RequestActionException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * RTB接入bid请求处理抽象类，以RTB方式接入接口实现都将继承此类
 * @author Wu Chengjun
 */
public abstract class BIDRequestHandler extends AdRequestHandler {
	
	private static Logger LOGGER = LoggerFactory.getLogger(BIDRequestHandler.class);
	
	/* (non-Javadoc)
	 * @see cn.falconnect.adserver.adapter.AdRequestHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) throws RequestHandleException {
		BidAdRequest bidRequest= null;
		BidAdResponse  bidResponse = null;
		try{
			String channel = getChannel(request);
			if(StringUtils.isEmpty(channel)){
				throw new RequestHandleException("无法获取请求中的接入渠道标识.");
			}
			HttpServletParser parser = getParser();
			if(parser == null){
				throw new RequestHandleException("缺省的监测消息解析实例没有初始化.");
			}
			
			IAdserverRequest adReq = parser.parse(request);
			if(adReq == null){
				throw new NullPointerException("AdRequest is null.");
			}
			
			if(adReq instanceof BidAdRequest){
				bidRequest =  (BidAdRequest)adReq;
				bidRequest.setChannelID(channel);
				bidResponse = (BidAdResponse) getRequestAction().doRequest(bidRequest);
				if(bidResponse == null){
					throw new NullResponseException();
				}
				handleResponse(response, parser, bidRequest, bidResponse);
			}else{
				throw new RequestHandleException("The Request is not support. class:" + adReq.getClass().getName());
			}
		}catch(AdRequestParseException | RequestActionException | RequestHandleException ex){
			handleExceptionResponse(ex, response);
		}catch(Exception ex){
			ex.printStackTrace();
			throw new RequestHandleException("处理bid请求出现异常.", ex);
		}finally {
			logAdBidEvent(bidRequest, bidResponse);
		}
	}

	/**
	 * 记录Bid请求处理事件
	 * @param request
	 * @param response
	 */
	public void logAdBidEvent(BidAdRequest request, BidAdResponse response){
		// TODO 后期整理完善
	}
	
}
